/**
 * 
 */
package com.cms.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.cms.common.ResultMsg;
import com.cms.constant.CmsConstant;
import com.cms.pojo.Article;
import com.cms.pojo.Category;
import com.cms.pojo.Channel;
import com.cms.pojo.User;
import com.cms.pojo.vo.ArticleVo;
import com.cms.service.ArticleService;
import com.github.pagehelper.PageInfo;

/**
 * @author zhaoyan
 *
 * 2020年1月9日
 */
@RequestMapping("article")
@Controller
public class ArticleController {
	
	
	@Autowired
	private ArticleService articleService;
	
	@Value("${upload.path}")
	private String upLoadPath;
	
	
	@RequestMapping("findArticle")
	public String articleList(Model m,ArticleVo articleVo,@RequestParam(defaultValue = "1")Integer pageNum) {
		
		PageInfo<Article> articlePage = articleService.findArticle(articleVo,pageNum);
		
		m.addAttribute("articlePage", articlePage);
		
		return "show/articlelist";
	}

	
	@RequestMapping("getArticle")
	@ResponseBody
	public ResultMsg<Article> getArticle(Integer articleId) {
		Article article = articleService.getArticle(articleId);
		if(article == null) 
			return new ResultMsg<Article>(CmsConstant.ARTICLE_STATUS_FAILURE,CmsConstant.ARTICLE_MSG_ERROR , null);
		return new ResultMsg<Article>(CmsConstant.ARTICLE_STATUS_SUCCESS, null, article);
	}
	
	@RequestMapping("checkArticle")
	@ResponseBody
	public ResultMsg<String> checkArticle( Integer id, Integer status){
		
		Integer num = articleService.checkArticle(id,status);
		
		return new ResultMsg<String>(num, null, null);
		
	}
	@RequestMapping("setHot")
	@ResponseBody
	public ResultMsg<String> setHot( Integer id, Integer hot){
		
		Integer num = articleService.setHot(id,hot);
		
		return new ResultMsg<String>(num, null, null);
		
	}
	
	
	@RequestMapping("toHome")
	public String toHome() {
		
		return "home/home";
	}
	
	
	@RequestMapping("addArticle")
	public String toAddArticle(Model m) {
		
		List<Channel> channelList =  articleService.showChannel();
		
		//System.err.println("!!");
		
		m.addAttribute("channels", channelList);
		
		return "show/addArticle";
	}
	
	
	@RequestMapping("findCategory")
	@ResponseBody
	public ResultMsg<List<Category>> findCategory(Integer channelID){
		
		 List<Category> catList = articleService.findCategoryById(channelID);
		 
		// System.out.println(channelID);
		 
		 if(catList == null) 
			 new ResultMsg<Object>(15, "未存在的分类", null);
		 
		return new ResultMsg<List<Category>>(null, null, catList);
	}
	
	@RequestMapping("addArticleFile")
	@ResponseBody
	public ResultMsg<String> addArticleFile(HttpSession session, Article article ,@RequestParam("imgFile")MultipartFile imgFile){
	
		System.out.println(article);
		
		System.out.println(imgFile.getOriginalFilename());
		
		try {
			String upLoad = upLoad(imgFile);
			article.setPicture(upLoad);
			
			User loginUser = (User) session.getAttribute(CmsConstant.USER_KEY);
			
			if( loginUser == null ) 
				return new ResultMsg<String>(null, "请先登录", null);
			Integer id = loginUser.getId();
			article.setUser_id(id);
			
			int num  = articleService.addArticle(article);
			
			System.out.println(num);
			
			return new ResultMsg<String>(0, "发布成功", "");
			
		}  catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		   
		
		return new ResultMsg<String>(3, "发布失败", "");
	}
	
	
	@RequestMapping("findArticleByUid")
	public String findArticleByUid(HttpSession session,Model m,@RequestParam(defaultValue = "1")Integer pageNum){
		
		User user  = (User) session.getAttribute(CmsConstant.USER_KEY);
		
		System.out.println(user);
		
		PageInfo<Article> articlePage = articleService.findArticleByUid(user.getId(),pageNum);
		
		m.addAttribute("articlePage", articlePage);
		
		return "show/userarticles";
		
	}
	
	@RequestMapping("delArticleById")
	@ResponseBody
	public ResultMsg<String> delArticleById(Integer id){
		
		Integer num = articleService.delArticleById(id);
		
		if(num>0) 
			return new ResultMsg<String>(0, "删除成功", null);
		return new ResultMsg<String>(1, "删除失败", null);
	}
	


	/**
	 * @param imgFile
	 * @return
	 * @throws IOException 
	 * @throws IllegalStateException 
	 */
	private String upLoad(MultipartFile imgFile) throws IllegalStateException, IOException {
		// TODO Auto-generated method stub
		
		//	判断文件是否为空
		if(imgFile.getOriginalFilename()==null||imgFile.getOriginalFilename() == "")
			return "";
		
		//	创建的文件夹
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd");
		
		String todaySrc = sdf.format(new Date());
		
		File filePath = new File(upLoadPath +"/"+  todaySrc);
		
		if( !filePath.exists() )
			filePath.mkdirs();
		
		//	第一步，获取原来的文件名称
		String originalFilename = imgFile.getOriginalFilename();
		
		//	获取计算机的扩展名
		
		String suffixeName = originalFilename.substring(originalFilename.lastIndexOf(".")) ;
		
		//	第二步， 获取随机的文件名
		
		String randomFileName = UUID.randomUUID().toString() + suffixeName;
		
		//	第三步，把文件写入目标位置
		
		imgFile.transferTo(new File(filePath + "/"+ randomFileName));
		
		//	第四部，返回文件的路径
		
		return todaySrc + "/" + randomFileName;
	}
	
	
	
}
